﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace Warlock.GameStuff.Network
{
    public class WarlockProt
    {
        public enum Packettype : byte 
        {
            newPlayer = 1,
            PlayerUpdate = 2,
            Playerlist = 3,
            PlayerlistUpdate = 4,
            ID = 5,
            DNSGAME = 6
        }

        public static String analyse(Socket TCPSock , out Packettype Type)
        {
            String message = "";
            byte[] recbytes = new byte[4];
            byte[] bytetype = new byte[1];
            char[] chars;
            int bytesRcvd;
            TCPSock.Receive(recbytes);
            int length = recbytes[0] + recbytes[1] + recbytes[2] + recbytes[3];
            TCPSock.Receive(bytetype);
            recbytes = new byte[length];
            bytesRcvd = TCPSock.Receive(recbytes);
            chars = new char[bytesRcvd];
            Decoder dec = Encoding.UTF8.GetDecoder();
            int charLen = dec.GetChars(recbytes, 0, bytesRcvd, chars, 0);
            message = new string(chars);

            Type = (Packettype)bytetype[0];
            return message;
            
        }
        public static void Packetbuilder(String text,Packettype Type , out byte[] byte1, out byte[] byte2, out byte[] byte3)
        {
            byte1 = BitConverter.GetBytes(text.Length);
            while (true)
            {
                if (byte1.Count() < 4)
                {
                    byte[] nebyte = new byte[4];
                    byte1.CopyTo(nebyte, 0);
                    byte1 = nebyte;
                }
               else
                {
                    break;
                }
            }
            byte bytetype = (byte)Type;
            byte2 = new byte[1]; 
            byte2[0] = bytetype;
            //Console.WriteLine(sizeof(char));
            byte3 = System.Text.Encoding.UTF8.GetBytes(text);
            //Console.WriteLine(byte3);
        }
    }

}
